package com.nbjtjc.safe.api.sys;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.URLUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nbjtjc.safe.oss.service.OSSFactory;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.mapper.sys.SysFileMapper;
import com.nbjtjc.safe.model.sys.SysFile;
import com.nbjtjc.safe.service.sys.SysFileService;
import com.nbjtjc.safe.util.FileUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 文件上传下载，现在已经过时，走阿里云的oss
 */
@Deprecated
@RestController
@RequestMapping(value = "/file")
@CrossOrigin("*")
public class FileController {
    private static Logger logger= LoggerFactory.getLogger(FileController.class);
    @Autowired
    private SysFileService fileService;
    @Autowired
    private SysFileMapper sysFileMapper;
    @Autowired
    private FileUtil fileUtil;

    @Autowired
    private OSSFactory ossFactory;
    @Value("${aliyun.oss.domain}")
    private String ossDomain;
    @RequestMapping(value = "upload", method = {RequestMethod.POST})
    @ApiOperation("上传文件，key选择file")
    public Result<List<SysFile>> uploadFile(HttpServletRequest request, SysFile pic) {
        Result<List<SysFile>> result = new Result<>();
        List<SysFile> files = new ArrayList<>();
        try {
            // 解析器解析request的上下文未登录或者过期
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 先判断request中是否包含mutipart类型的数据
            if (multipartResolver.isMultipart(request)) {
                // 再将request中得数据转化成multipart类型的数据f
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                List<MultipartFile> multipartFiles = multiRequest.getFiles("file");
                Iterator iterator = multiRequest.getFileNames();
                while (iterator.hasNext()) {
                    MultipartFile file = multiRequest.getFile((String) iterator.next());
                    if (!file.isEmpty()) {
                        Result<SysFile> fileResult = fileService.uploadFile(file, pic);
                        if (fileResult.isSuccess()) {
                            files.add(fileResult.getData());
                        } else {
                            result.setFalse(fileResult.getMessage());
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setFalse("上传失败" + e.getMessage());
        }
        result.setData(files);
        return result;
    }

    @RequestMapping(value = "uploadOSS", method = {RequestMethod.POST})
    @ApiOperation("上传文件，key选择file")
    public Result<List<SysFile>> uploadOSS(HttpServletRequest request, SysFile pic) {
        long time=System.currentTimeMillis();
        Result<List<SysFile>> result = new Result<>();
        List<SysFile> files = new ArrayList<>();
        try {
            // 解析器解析request的上下文未登录或者过期
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 先判断request中是否包含mutipart类型的数据
            if (multipartResolver.isMultipart(request)) {
                // 再将request中得数据转化成multipart类型的数据f
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                List<MultipartFile> multipartFiles = multiRequest.getFiles("file");
                Iterator iterator = multiRequest.getFileNames();
                while (iterator.hasNext()) {
                    MultipartFile file = multiRequest.getFile((String) iterator.next());
                    if (!file.isEmpty()) {
                        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                        logger.error("开始时间1："+(System.currentTimeMillis()-time));
                        String url = ossFactory.build().uploadSuffix(file.getInputStream(), suffix);
                        logger.error("开始时间2："+(System.currentTimeMillis()-time));

                        SysFile fileResult = fileService.uploadFile(url, file.getOriginalFilename(), pic);
                        logger.error("开始时间3："+(System.currentTimeMillis()-time));

                        files.add(fileResult);

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setFalse("上传失败" + e.getMessage());
        }
        result.setData(files);
        return result;
    }

    @RequestMapping(value = "/download", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation("下载文件，上传文件的id")
    public void downloadFile(SysFile sysFile, HttpServletResponse response) throws FileNotFoundException {
        SysFile file = fileService.findFile(sysFile);
        file.setPercentage(sysFile.getPercentage());
        if (file != null) {
            BufferedInputStream bis = null;
            byte[] buff = new byte[1024];
            java.io.File targetFile = fileUtil.getFile(file);
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            response.setContentType("image/jpeg");
            response.setHeader("Content-Disposition", "attachment;filename=" + file.getFileName());
            try (ServletOutputStream outputStream = response.getOutputStream()) {
                bis = new BufferedInputStream(new FileInputStream(targetFile));
                int i = bis.read(buff);
                while (i != -1) {
                    outputStream.write(buff, 0, i);
                    outputStream.flush();
                    i = bis.read(buff);
                }
            } catch (IOException e) {
                throw new FileNotFoundException("输出文件时报错：" + e.getMessage());
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            throw new FileNotFoundException("文件没有找到");
        }
    }

    @RequestMapping(value = "/update", method = {RequestMethod.POST})
    public Result<SysFile> updateFile(SysFile sysFile) {
        Result<SysFile> result = new Result<>();
        try {

            result = fileService.update(sysFile);
        } catch (Exception e) {
            e.printStackTrace();
            result.setFalse("错误信息：" + e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/delete", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation("删除文件")
    public Result<Boolean> delete(SysFile sysFile) {
        Result<Boolean> result = new Result();
        try {
            if (!fileService.delete(sysFile)) {
                result.setFalse("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setFalse("错误信息：" + e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/find", method = {RequestMethod.POST})
    @ApiOperation("查找对应文件，需要填写contentId和contentType字段")
    public Result find(SysFile sysFile) {
        Result result = new Result();
        if (ObjectUtil.isNull(sysFile)
                || ObjectUtil.isNull(sysFile.getContentId())
                || ObjectUtil.isNull(sysFile.getContentType())
                || sysFile.getContentType().equals(-1)) {
            result.setFalse("关键字段不能为空");
            return result;
        }
        Example example = new Example(SysFile.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("contentId", sysFile.getContentId());
        criteria.andEqualTo("contentType", sysFile.getContentType());
        criteria.andEqualTo("history",0);
        if (ObjectUtil.isNotNull(sysFile.getUserId())) {
            criteria.andEqualTo("userId", sysFile.getUserId());
        }
        List<SysFile> sysFiles = sysFileMapper.selectByExample(example);
        result.setData(sysFiles);
        return result;
    }

    @RequestMapping(value = "/findPage", method = {RequestMethod.POST})
    @ApiOperation("查找对应文件，需要填写contentId和contentType字段")
    public Result findPage(SysFile sysFile){
        Result result =new Result();

        PageHelper.startPage(sysFile.getPageCurrent(),sysFile.getPageSize());
        List<SysFile> sysFiles=sysFileMapper.search(sysFile);
        sysFiles.forEach(file->{
            String path=file.getPath();
            file.setOriUrl(ossDomain+"/"+path.substring(0,path.lastIndexOf("/")+1)+ URLUtil.encode(path.substring(path.lastIndexOf("/")+1,path.length())));
        });
        result.setData(new PageInfo<>(sysFiles));
        return result;
    }

    public static void main(String[] args) {
        String path="safe360/2021/5/8/高新制造业-12021-5-823058.docx";
        System.out.println(path.substring(0,path.lastIndexOf("/")+1));
        System.out.println(path.substring(path.lastIndexOf("/")+1,path.length()));
    }
}
